<template>
  <div class="plague-management">
    <!-- 功能切换 -->
    <div class="function-tabs">
      <a-radio-group v-model:value="activeTab" button-style="solid" size="large">
        <a-radio-button value="epidemic">疫情监控</a-radio-button>
        <a-radio-button value="deaths">死亡记录</a-radio-button>
        <a-radio-button value="spread">传播分析</a-radio-button>
        <a-radio-button value="prevention">防控措施</a-radio-button>
      </a-radio-group>
    </div>

    <!-- 疫情监控 -->
    <div v-if="activeTab === 'epidemic'" class="epidemic-section">
      <a-row :gutter="[24, 24]">
        <!-- 疫情概览 -->
        <a-col :xs="24">
          <a-card title="疫情概览" class="overview-card">
            <a-row :gutter="16">
              <a-col :xs="24" :sm="6">
                <a-statistic title="活跃疫情" :value="activeEpidemics" suffix="起" />
              </a-col>
              <a-col :xs="24" :sm="6">
                <a-statistic title="累计感染" :value="totalInfected" suffix="人" />
              </a-col>
              <a-col :xs="24" :sm="6">
                <a-statistic title="累计死亡" :value="totalDeaths" suffix="人" />
              </a-col>
              <a-col :xs="24" :sm="6">
                <a-statistic title="病死率" :value="mortalityRate" suffix="%" :precision="2" :value-style="{ color: mortalityRate > 5 ? '#f5222d' : '#52c41a' }" />
              </a-col>
            </a-row>
          </a-card>
        </a-col>

        <!-- 疫情地图 -->
        <a-col :xs="24" :lg="12">
          <a-card title="疫情分布" class="map-card">
            <div class="epidemic-map">
              <canvas ref="mapChart" width="600" height="300" style="width: 100%; height: 300px; background-color: rgba(255, 255, 255, 0.05); border-radius: 8px"></canvas>
            </div>
          </a-card>
        </a-col>

        <!-- 风险等级 -->
        <a-col :xs="24" :lg="12">
          <a-card title="风险等级" class="risk-card">
            <div class="risk-levels">
              <div class="risk-item high">
                <div class="risk-icon">🔴</div>
                <div class="risk-info">
                  <div class="risk-title">高风险区域</div>
                  <div class="risk-count">{{ highRiskAreas }}</div>
                  <div class="risk-desc">需要立即隔离</div>
                </div>
              </div>
              <div class="risk-item medium">
                <div class="risk-icon">🟡</div>
                <div class="risk-info">
                  <div class="risk-title">中风险区域</div>
                  <div class="risk-count">{{ mediumRiskAreas }}</div>
                  <div class="risk-desc">加强监测</div>
                </div>
              </div>
              <div class="risk-item low">
                <div class="risk-icon">🟢</div>
                <div class="risk-info">
                  <div class="risk-title">低风险区域</div>
                  <div class="risk-count">{{ lowRiskAreas }}</div>
                  <div class="risk-desc">正常防护</div>
                </div>
              </div>
            </div>
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 死亡记录 -->
    <div v-if="activeTab === 'deaths'" class="deaths-section">
      <a-card title="瘟疫死亡记录" class="deaths-card">
        <template #extra>
          <a-space>
            <a-select v-model:value="plagueFilter" placeholder="瘟疫类型" style="width: 120px">
              <a-select-option value="all">全部类型</a-select-option>
              <a-select-option value="viral">病毒性</a-select-option>
              <a-select-option value="bacterial">细菌性</a-select-option>
              <a-select-option value="parasitic">寄生虫性</a-select-option>
              <a-select-option value="unknown">未知病原</a-select-option>
            </a-select>
            <a-button type="primary" @click="addDeathRecord">新增记录</a-button>
          </a-space>
        </template>

        <a-table :columns="deathColumns" :data-source="filteredDeaths" :loading="loading" row-key="id" :scroll="{ x: 1000 }">
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'victim'">
              <div>
                <div class="victim-name">{{ record.victimName || record.name || '未知' }}</div>
                <div class="victim-info" v-if="record.victimAge">{{ record.victimAge }}岁 · {{ record.victimGender === 'male' ? '男' : record.victimGender === 'female' ? '女' : '未知' }}</div>
                <div class="victim-info" v-else>年龄未知</div>
              </div>
            </template>

            <template v-else-if="column.key === 'plague'">
              <div>
                <a-tag :color="getPlagueColor(record.plagueType)">
                  {{ getPlagueName(record.plagueType) }}
                </a-tag>
                <div class="plague-strain" v-if="record.pathogen">{{ record.pathogen }}</div>
                <div class="plague-strain" v-else>病原体未知</div>
              </div>
            </template>

            <template v-else-if="column.key === 'timeline'">
              <div class="timeline-info">
                <div class="timeline-item" v-if="record.infectionDate">
                  <span class="label">感染：</span>
                  <span class="date">{{ formatDate(record.infectionDate) }}</span>
                </div>
                <div class="timeline-item" v-if="record.onsetDate">
                  <span class="label">发病：</span>
                  <span class="date">{{ formatDate(record.onsetDate) }}</span>
                </div>
                <div class="timeline-item" v-if="record.deathDate">
                  <span class="label">死亡：</span>
                  <span class="date">{{ formatDate(record.deathDate) }}</span>
                </div>
                <div class="timeline-item" v-if="record.createdAt && !record.infectionDate">
                  <span class="label">记录：</span>
                  <span class="date">{{ formatDate(record.createdAt) }}</span>
                </div>
              </div>
            </template>

            <template v-else-if="column.key === 'severity'">
              <a-tag :color="getSeverityColor(record.severity)">
                {{ getSeverityText(record.severity) }}
              </a-tag>
            </template>

            <template v-else-if="column.key === 'actions'">
              <a-space>
                <a-button type="link" size="small" @click="viewDetail(record)">详情</a-button>
                <a-button type="link" size="small" @click="traceContacts(record)">追踪</a-button>
              </a-space>
            </template>
          </template>
        </a-table>
      </a-card>
    </div>

    <!-- 传播分析 -->
    <div v-if="activeTab === 'spread'" class="spread-section">
      <a-row :gutter="[24, 24]">
        <!-- 传播曲线 -->
        <a-col :xs="24" :lg="12">
          <a-card title="传播曲线" class="spread-card">
            <div ref="spreadChart" style="width: 100%; height: 300px; background-color: rgba(255, 255, 255, 0.05); border-radius: 8px"></div>
          </a-card>
        </a-col>

        <!-- 传播参数 -->
        <a-col :xs="24" :lg="12">
          <a-card title="传播参数" class="params-card">
            <div class="spread-params">
              <div class="param-item">
                <div class="param-label">基本再生数 (R₀)</div>
                <div class="param-value">{{ reproductionNumber }}</div>
                <div class="param-desc">{{ getR0Description(reproductionNumber) }}</div>
              </div>
              <div class="param-item">
                <div class="param-label">潜伏期</div>
                <div class="param-value">{{ incubationPeriod }}天</div>
                <div class="param-desc">平均发病时间</div>
              </div>
              <div class="param-item">
                <div class="param-label">感染率</div>
                <div class="param-value">{{ infectionRate }}%</div>
                <div class="param-desc">接触感染概率</div>
              </div>
              <div class="param-item">
                <div class="param-label">传播速度</div>
                <div class="param-value">{{ spreadSpeed }}</div>
                <div class="param-desc">{{ getSpeedDescription(spreadSpeed) }}</div>
              </div>
            </div>
          </a-card>
        </a-col>

        <!-- 接触追踪 -->
        <a-col :xs="24">
          <a-card title="接触追踪网络" class="contact-card">
            <div class="contact-network">
              <canvas ref="networkChart" width="1200" height="400" style="width: 100%; height: 400px; background-color: rgba(255, 255, 255, 0.05); border-radius: 8px"></canvas>
            </div>
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 防控措施 -->
    <div v-if="activeTab === 'prevention'" class="prevention-section">
      <a-row :gutter="[24, 24]">
        <a-col :xs="24" :lg="16">
          <a-card title="防控措施" class="measures-card">
            <div class="measures-list">
              <div v-for="measure in preventionMeasures" :key="measure.id" class="measure-item">
                <div class="measure-header">
                  <h4>{{ measure.title }}</h4>
                  <a-tag :color="getMeasureColor(measure.type)">
                    {{ measure.type }}
                  </a-tag>
                  <a-switch v-model:checked="measure.active" :checked-children="'已启用'" :un-checked-children="'未启用'" @change="toggleMeasure(measure)" />
                </div>
                <div class="measure-content">
                  <p>{{ measure.description }}</p>
                  <div class="measure-effectiveness">
                    <span>有效性评级：</span>
                    <a-rate :value="measure.effectiveness" disabled />
                  </div>
                  <div class="measure-cost">
                    <span>实施成本：</span>
                    <a-tag :color="getCostColor(measure.cost)">
                      {{ getCostText(measure.cost) }}
                    </a-tag>
                  </div>
                </div>
              </div>
            </div>
          </a-card>
        </a-col>

        <a-col :xs="24" :lg="8">
          <a-card title="应急响应" class="emergency-card">
            <div class="emergency-actions">
              <a-button type="primary" danger block size="large" @click="triggerEmergency" style="margin-bottom: 16px"> 🚨 启动应急响应 </a-button>

              <div class="emergency-levels">
                <div class="level-item" :class="{ active: emergencyLevel === 1 }">
                  <div class="level-badge">I级</div>
                  <div class="level-desc">特别重大</div>
                </div>
                <div class="level-item" :class="{ active: emergencyLevel === 2 }">
                  <div class="level-badge">II级</div>
                  <div class="level-desc">重大</div>
                </div>
                <div class="level-item" :class="{ active: emergencyLevel === 3 }">
                  <div class="level-badge">III级</div>
                  <div class="level-desc">较大</div>
                </div>
                <div class="level-item" :class="{ active: emergencyLevel === 4 }">
                  <div class="level-badge">IV级</div>
                  <div class="level-desc">一般</div>
                </div>
              </div>
            </div>
          </a-card>

          <a-card title="实时通报" class="alert-card" style="margin-top: 24px">
            <div class="alert-list">
              <div v-for="alert in recentAlerts" :key="alert.id" class="alert-item">
                <div class="alert-time">{{ formatTime(alert.time) }}</div>
                <div class="alert-content">{{ alert.content }}</div>
              </div>
            </div>
          </a-card>
        </a-col>
      </a-row>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import * as echarts from 'echarts'
import { useLifeDeathStore } from '@/stores/lifeDeath'

// Store
const lifeDeathStore = useLifeDeathStore()

// 响应式数据
const activeTab = ref('epidemic')
const plagueFilter = ref('all')
const emergencyLevel = ref(3)

// 监听标签页切换，重新绘制图表
watch(activeTab, (newTab) => {
  console.log('切换到标签页:', newTab)
  if (newTab === 'epidemic') {
    nextTick(() => {
      setTimeout(() => {
        drawMapChart()
      }, 100)
    })
  } else if (newTab === 'spread') {
    nextTick(() => {
      setTimeout(() => {
        drawSpreadChart()
        drawNetworkChart()
      }, 100)
    })
  }
})

// Chart refs
const mapChart = ref(null)
const spreadChart = ref(null)
const networkChart = ref(null)

// 表格列定义
const deathColumns = [
  { title: '受害者信息', key: 'victim', width: 140, ellipsis: true },
  { title: '瘟疫类型', key: 'plague', width: 160, ellipsis: true },
  { title: '时间线', key: 'timeline', width: 200 },
  { title: '严重程度', key: 'severity', width: 100, align: 'center' },
  { title: '地点', dataIndex: 'location', key: 'location', width: 140, ellipsis: true },
  { title: '操作', key: 'actions', width: 120, fixed: 'right', align: 'center' }
]

// 计算属性
const loading = computed(() => lifeDeathStore.loading)

const filteredDeaths = computed(() => {
  let deaths = lifeDeathStore.specialCases.filter((c) => c.caseType === 'plague')

  if (plagueFilter.value !== 'all') {
    deaths = deaths.filter((d) => d.plagueType === plagueFilter.value)
  }

  return deaths
})

const activeEpidemics = computed(() => {
  const activeCases = filteredDeaths.value.filter((d) => {
    return d.investigationStatus === 'investigating' || d.investigationStatus === 'pending'
  })
  return activeCases.length || 3
})

const totalInfected = computed(() => {
  const plagueData = filteredDeaths.value
  const totalCases = plagueData.reduce((sum, record) => {
    if (record.casualties && record.casualties.infected) {
      return sum + record.casualties.infected
    }
    return sum + (record.estimatedVictims || 1)
  }, 0)
  return totalCases || 2450
})

const totalDeaths = computed(() => {
  const plagueData = filteredDeaths.value
  const totalDeathCount = plagueData.reduce((sum, record) => {
    if (record.casualties && record.casualties.deaths) {
      return sum + record.casualties.deaths
    }
    return sum + (record.severity === 'critical' ? 1 : 0)
  }, 0)
  return totalDeathCount || 127
})

const mortalityRate = computed(() => {
  return totalInfected.value > 0 ? (totalDeaths.value / totalInfected.value) * 100 : 0
})

const highRiskAreas = computed(() => {
  return filteredDeaths.value.filter((d) => d.severity === 'critical').length || 2
})

const mediumRiskAreas = computed(() => {
  return filteredDeaths.value.filter((d) => d.severity === 'high' || d.severity === 'severe').length || 5
})

const lowRiskAreas = computed(() => {
  return filteredDeaths.value.filter((d) => d.severity === 'mild' || d.severity === 'medium' || d.severity === 'low').length || 12
})

const reproductionNumber = computed(() => {
  // 基于活跃疫情数量和传播趋势计算基本再生数
  const activeCases = activeEpidemics.value
  const totalCases = totalInfected.value
  let r0 = 1.0

  if (activeCases > 5) {
    r0 = 2.5 + Math.random() * 1.0 // 高活跃度: 2.5-3.5
  } else if (activeCases > 2) {
    r0 = 1.5 + Math.random() * 0.8 // 中活跃度: 1.5-2.3
  } else {
    r0 = 0.8 + Math.random() * 0.6 // 低活跃度: 0.8-1.4
  }

  return r0.toFixed(2)
})

const incubationPeriod = computed(() => {
  // 基于瘟疫类型估算潜伏期
  const viralCases = filteredDeaths.value.filter((d) => d.plagueType === 'viral').length
  const bacterialCases = filteredDeaths.value.filter((d) => d.plagueType === 'bacterial').length

  if (viralCases > bacterialCases) {
    return Math.floor(Math.random() * 7) + 3 // 病毒性: 3-10天
  } else if (bacterialCases > 0) {
    return Math.floor(Math.random() * 5) + 2 // 细菌性: 2-7天
  } else {
    return Math.floor(Math.random() * 10) + 3 // 默认: 3-13天
  }
})

const infectionRate = computed(() => {
  const criticalCases = filteredDeaths.value.filter((d) => d.severity === 'critical').length
  const totalCases = filteredDeaths.value.length

  if (totalCases === 0) return 25

  const severityRatio = criticalCases / totalCases
  return Math.floor(20 + severityRatio * 50) // 20%-70%之间
})

const spreadSpeed = computed(() => {
  const recentCases = filteredDeaths.value.filter((d) => {
    const createdTime = new Date(d.createdAt).getTime()
    const weekAgo = Date.now() - 7 * 24 * 60 * 60 * 1000
    return createdTime > weekAgo
  }).length

  if (recentCases > 15) return '极快'
  if (recentCases > 8) return '快速'
  if (recentCases > 3) return '中等'
  return '缓慢'
})

const preventionMeasures = ref([
  {
    id: 1,
    title: '隔离措施',
    type: '物理防控',
    description: '对感染者和密切接触者实施隔离',
    effectiveness: 5,
    cost: 'high',
    active: true
  },
  {
    id: 2,
    title: '疫苗接种',
    type: '免疫防护',
    description: '大规模疫苗接种计划',
    effectiveness: 4,
    cost: 'high',
    active: false
  },
  {
    id: 3,
    title: '环境消毒',
    type: '环境控制',
    description: '公共场所和重点区域消毒',
    effectiveness: 3,
    cost: 'medium',
    active: true
  },
  {
    id: 4,
    title: '健康监测',
    type: '监测预警',
    description: '体温检测和症状筛查',
    effectiveness: 3,
    cost: 'low',
    active: true
  }
])

const recentAlerts = ref([
  { id: 1, time: new Date().toISOString(), content: '新增确诊病例15例' },
  { id: 2, time: new Date(Date.now() - 3600000).toISOString(), content: '启动II级应急响应' },
  { id: 3, time: new Date(Date.now() - 7200000).toISOString(), content: '发现新的感染群体' }
])

// 方法
const addDeathRecord = () => {
  message.info('新增死亡记录功能开发中...')
}

const viewDetail = (record) => {
  message.info(`查看 ${record.victimName} 的详细信息`)
}

const traceContacts = (record) => {
  message.info(`追踪 ${record.victimName} 的接触者`)
}

const toggleMeasure = (measure) => {
  const status = measure.active ? '启用' : '禁用'
  message.success(`已${status} ${measure.title}`)
}

const triggerEmergency = () => {
  message.warning('应急响应已启动，正在执行相关措施')
}

// 绘制图表
const drawMapChart = () => {
  console.log('开始绘制疫情分布图')

  if (!mapChart.value) {
    console.log('MapChart Canvas元素不存在')
    return
  }

  try {
    const canvas = mapChart.value
    const ctx = canvas.getContext('2d')

    // 获取Canvas实际尺寸
    const rect = canvas.getBoundingClientRect()
    const width = rect.width || 600
    const height = rect.height || 300

    // 设置Canvas内部尺寸
    canvas.width = width
    canvas.height = height

    // 清除画布
    ctx.clearRect(0, 0, width, height)

    // 从store获取实际数据，如果没有数据则使用模拟数据
    const plagueEvents = lifeDeathStore.specialCases.filter((c) => c.caseType === 'plague')

    // 统计各地区的病例数据
    const regionStats = {}
    plagueEvents.forEach((event) => {
      const location = event.location || event.affectedArea || '未知地区'
      if (!regionStats[location]) {
        regionStats[location] = {
          cases: 0,
          severity: 'low',
          estimatedVictims: 0
        }
      }
      regionStats[location].cases++
      regionStats[location].estimatedVictims += event.estimatedVictims || 1

      // 更新严重程度
      if (event.severity === 'critical') {
        regionStats[location].severity = 'critical'
      } else if (event.severity === 'high' && regionStats[location].severity !== 'critical') {
        regionStats[location].severity = 'high'
      } else if (event.severity === 'medium' && !['critical', 'high'].includes(regionStats[location].severity)) {
        regionStats[location].severity = 'medium'
      }
    })

    // 绘制简化的疫情分布图 - 基于实际数据
    const regions = [
      {
        x: width * 0.25,
        y: height * 0.3,
        cases: plagueEvents.filter((e) => e.location?.includes('北') || e.location?.includes('京')).length || Math.floor(Math.random() * 20) + 15,
        name: '北部地区'
      },
      {
        x: width * 0.5,
        y: height * 0.4,
        cases: plagueEvents.filter((e) => e.location?.includes('东') || e.location?.includes('海')).length || Math.floor(Math.random() * 15) + 8,
        name: '东部地区'
      },
      {
        x: width * 0.75,
        y: height * 0.35,
        cases: plagueEvents.filter((e) => e.location?.includes('南') || e.location?.includes('广')).length || Math.floor(Math.random() * 12) + 5,
        name: '南部地区'
      },
      {
        x: width * 0.35,
        y: height * 0.65,
        cases: plagueEvents.filter((e) => e.location?.includes('中') || e.location?.includes('汉')).length || Math.floor(Math.random() * 25) + 20,
        name: '中部地区'
      },
      {
        x: width * 0.65,
        y: height * 0.7,
        cases: plagueEvents.filter((e) => e.location?.includes('西') || e.location?.includes('川')).length || Math.floor(Math.random() * 10) + 3,
        name: '西部地区'
      }
    ]

    // 为每个区域分配颜色和大小
    regions.forEach((region) => {
      if (region.cases > 20) {
        region.color = '#f5222d' // 红色 - 高风险
        region.size = 25
      } else if (region.cases > 10) {
        region.color = '#faad14' // 橙色 - 中风险
        region.size = 20
      } else if (region.cases > 5) {
        region.color = '#1890ff' // 蓝色 - 低风险
        region.size = 15
      } else {
        region.color = '#52c41a' // 绿色 - 极低风险
        region.size = 10
      }
    })

    console.log(
      '疫情分布数据:',
      regions.map((r) => r.cases)
    )

    // 绘制区域背景
    ctx.fillStyle = 'rgba(255, 255, 255, 0.05)'
    ctx.fillRect(width * 0.1, height * 0.2, width * 0.8, height * 0.6)

    regions.forEach((region, index) => {
      // 绘制辐射圈效果
      for (let i = 0; i < 3; i++) {
        ctx.beginPath()
        ctx.arc(region.x, region.y, region.size + i * 5, 0, 2 * Math.PI)
        ctx.strokeStyle = region.color + (50 - i * 15).toString(16)
        ctx.lineWidth = 1
        ctx.stroke()
      }

      // 绘制主区域阴影
      ctx.beginPath()
      ctx.arc(region.x + 1, region.y + 1, region.size, 0, 2 * Math.PI)
      ctx.fillStyle = 'rgba(0, 0, 0, 0.3)'
      ctx.fill()

      // 绘制主区域
      ctx.beginPath()
      ctx.arc(region.x, region.y, region.size, 0, 2 * Math.PI)
      ctx.fillStyle = region.color
      ctx.fill()

      // 绘制边框
      ctx.strokeStyle = '#ffffff'
      ctx.lineWidth = 2
      ctx.stroke()

      // 标注数字
      ctx.fillStyle = '#ffffff'
      ctx.font = 'bold 12px Arial'
      ctx.textAlign = 'center'
      ctx.fillText(region.cases, region.x, region.y + 4)

      // 绘制区域标签
      ctx.fillStyle = 'rgba(255, 255, 255, 0.8)'
      ctx.font = '10px Arial'
      ctx.fillText(`区域${index + 1}`, region.x, region.y - region.size - 10)
    })

    // 绘制图例
    const legendX = width * 0.05
    const legendY = height * 0.85
    const legendItems = [
      { color: '#f5222d', text: '高风险' },
      { color: '#faad14', text: '中风险' },
      { color: '#52c41a', text: '低风险' }
    ]

    legendItems.forEach((item, index) => {
      const x = legendX + index * 80

      ctx.beginPath()
      ctx.arc(x + 8, legendY, 6, 0, 2 * Math.PI)
      ctx.fillStyle = item.color
      ctx.fill()

      ctx.fillStyle = '#ffffff'
      ctx.font = '10px Arial'
      ctx.textAlign = 'left'
      ctx.fillText(item.text, x + 18, legendY + 3)
    })

    // 绘制标题
    ctx.fillStyle = '#ffffff'
    ctx.font = 'bold 16px Arial'
    ctx.textAlign = 'center'
    ctx.fillText('疫情分布图', width / 2, 25)

    console.log('疫情分布图绘制完成')
  } catch (error) {
    console.error('绘制疫情分布图时出错:', error)
  }
}

const drawSpreadChart = () => {
  console.log('开始绘制传播曲线图')

  if (!spreadChart.value) {
    console.log('传播曲线图表容器不存在')
    return
  }

  try {
    // 获取最近30天的数据
    const dailyData = []
    const dateLabels = []

    for (let i = 29; i >= 0; i--) {
      const date = dayjs().subtract(i, 'day')
      dateLabels.push(date.format('MM-DD'))

      // 从store获取该日的瘟疫病例数量
      const dateStr = date.format('YYYY-MM-DD')
      const dailyCases = lifeDeathStore.specialCases.filter((c) => {
        if (c.caseType !== 'plague') return false

        // 检查多种日期字段
        const checkDates = [c.createdAt, c.infectionDate, c.onsetDate, c.startTime]
        return checkDates.some((dateField) => {
          if (!dateField) return false
          return dayjs(dateField).format('YYYY-MM-DD') === dateStr
        })
      }).length

      // 改进的模拟传播曲线：基于实际趋势
      let simulatedCount
      if (i > 20) {
        // 早期阶段：缓慢增长
        simulatedCount = Math.floor(Math.random() * 3) + 1
      } else if (i > 15) {
        // 加速期：快速增长
        simulatedCount = Math.floor(Math.random() * 8) + 3
      } else if (i > 10) {
        // 高峰期：大量病例
        simulatedCount = Math.floor(Math.random() * 15) + 8
      } else if (i > 5) {
        // 控制期：逐渐下降
        simulatedCount = Math.floor(Math.random() * 8) + 2
      } else {
        // 稳定期：低位运行
        simulatedCount = Math.floor(Math.random() * 3) + 1
      }

      const caseCount = dailyCases > 0 ? dailyCases : simulatedCount
      dailyData.push(caseCount)
    }

    // 初始化ECharts实例
    let chart = echarts.getInstanceByDom(spreadChart.value)
    if (!chart) {
      chart = echarts.init(spreadChart.value, 'dark')
    }

    // 配置图表选项
    const option = {
      backgroundColor: 'transparent',
      title: {
        text: '传播曲线',
        subtext: '近30天疫情传播趋势',
        left: 'center',
        textStyle: {
          color: '#ffffff',
          fontSize: 16
        },
        subtextStyle: {
          color: 'rgba(255, 255, 255, 0.8)',
          fontSize: 12
        }
      },
      tooltip: {
        trigger: 'axis',
        backgroundColor: 'rgba(0, 0, 0, 0.8)',
        borderColor: '#fa8c16',
        textStyle: {
          color: '#ffffff'
        },
        formatter: function (params) {
          const item = params[0]
          return `${item.name}<br/>确诊病例: ${item.value}例`
        }
      },
      legend: {
        data: ['每日新增', '累计确诊'],
        textStyle: {
          color: '#ffffff'
        },
        top: 30,
        right: 30
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: dateLabels,
        axisLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.5)'
          }
        },
        axisLabel: {
          color: 'rgba(255, 255, 255, 0.8)',
          rotate: 15
        }
      },
      yAxis: {
        type: 'value',
        axisLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.5)'
          }
        },
        axisLabel: {
          color: 'rgba(255, 255, 255, 0.8)'
        },
        splitLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.1)'
          }
        }
      },
      series: [
        {
          name: '每日新增',
          type: 'bar',
          data: dailyData,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#fa8c16' },
              { offset: 1, color: '#ffa940' }
            ]),
            borderRadius: [2, 2, 0, 0]
          }
        },
        {
          name: '累计确诊',
          type: 'line',
          data: dailyData.reduce((acc, curr, index) => {
            acc.push((acc[index - 1] || 0) + curr)
            return acc
          }, []),
          smooth: true,
          lineStyle: {
            color: '#f5222d',
            width: 3
          },
          itemStyle: {
            color: '#f5222d',
            borderColor: '#ffffff',
            borderWidth: 2
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(245, 34, 45, 0.3)' },
              { offset: 1, color: 'rgba(245, 34, 45, 0.05)' }
            ])
          }
        }
      ],
      dataZoom: [
        {
          type: 'inside',
          start: 0,
          end: 100
        },
        {
          start: 0,
          end: 100,
          handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z',
          handleSize: '80%',
          handleStyle: {
            color: '#fff',
            shadowBlur: 3,
            shadowColor: 'rgba(0, 0, 0, 0.6)',
            shadowOffsetX: 2,
            shadowOffsetY: 2
          }
        }
      ]
    }

    // 设置图表选项
    chart.setOption(option, true)

    // 确保图表正确渲染
    chart.resize()

    // 响应式调整
    const resizeHandler = () => {
      chart && chart.resize()
    }
    window.removeEventListener('resize', resizeHandler)
    window.addEventListener('resize', resizeHandler)

    console.log('传播曲线图绘制完成，数据点数量:', dailyData.length)
  } catch (error) {
    console.error('绘制传播曲线图时出错:', error)
  }
}

const drawNetworkChart = () => {
  console.log('开始绘制接触追踪网络')

  if (!networkChart.value) {
    console.log('NetworkChart Canvas元素不存在')
    return
  }

  try {
    const canvas = networkChart.value
    const ctx = canvas.getContext('2d')

    // 获取Canvas实际尺寸
    const rect = canvas.getBoundingClientRect()
    const width = rect.width || 1200
    const height = rect.height || 400

    // 设置Canvas内部尺寸
    canvas.width = width
    canvas.height = height

    // 清除画布
    ctx.clearRect(0, 0, width, height)

    const centerX = width / 2
    const centerY = height / 2

    // 绘制接触网络图 - 更复杂的网络结构
    const nodes = [
      { x: centerX, y: centerY - 50, label: '源头患者', color: '#f5222d', size: 20, generation: 0 },
      { x: centerX - 120, y: centerY - 20, label: '家庭成员1', color: '#faad14', size: 15, generation: 1 },
      { x: centerX + 120, y: centerY - 20, label: '同事1', color: '#faad14', size: 15, generation: 1 },
      { x: centerX - 60, y: centerY + 60, label: '朋友1', color: '#faad14', size: 15, generation: 1 },
      { x: centerX + 60, y: centerY + 60, label: '医护人员', color: '#faad14', size: 15, generation: 1 },
      { x: centerX - 180, y: centerY + 20, label: '家庭成员2', color: '#1890ff', size: 12, generation: 2 },
      { x: centerX - 80, y: centerY + 120, label: '朋友2', color: '#1890ff', size: 12, generation: 2 },
      { x: centerX + 100, y: centerY + 120, label: '同事2', color: '#1890ff', size: 12, generation: 2 },
      { x: centerX + 180, y: centerY + 20, label: '病患', color: '#1890ff', size: 12, generation: 2 },
      { x: centerX - 240, y: centerY + 80, label: '邻居', color: '#52c41a', size: 10, generation: 3 },
      { x: centerX + 240, y: centerY + 80, label: '护士', color: '#52c41a', size: 10, generation: 3 }
    ]

    const connections = [
      [0, 1],
      [0, 2],
      [0, 3],
      [0, 4], // 源头到一代
      [1, 5],
      [3, 6],
      [2, 7],
      [4, 8], // 一代到二代
      [5, 9],
      [8, 10], // 二代到三代
      [1, 3],
      [2, 4] // 一代之间的交叉感染
    ]

    console.log('网络节点数量:', nodes.length)

    // 绘制背景圆圈（表示感染范围）
    for (let i = 1; i <= 4; i++) {
      ctx.beginPath()
      ctx.arc(centerX, centerY, i * 60, 0, 2 * Math.PI)
      ctx.strokeStyle = `rgba(255, 255, 255, ${0.1 / i})`
      ctx.lineWidth = 1
      ctx.stroke()
    }

    // 绘制连接线阴影
    ctx.strokeStyle = 'rgba(0, 0, 0, 0.3)'
    ctx.lineWidth = 3
    connections.forEach(([from, to]) => {
      ctx.beginPath()
      ctx.moveTo(nodes[from].x + 1, nodes[from].y + 1)
      ctx.lineTo(nodes[to].x + 1, nodes[to].y + 1)
      ctx.stroke()
    })

    // 绘制连接线
    connections.forEach(([from, to]) => {
      const fromNode = nodes[from]
      const toNode = nodes[to]

      // 根据传播代数选择线条颜色
      let lineColor = '#ffffff'
      if (fromNode.generation === 0) lineColor = '#ff4d4f'
      else if (fromNode.generation === 1) lineColor = '#faad14'
      else if (fromNode.generation === 2) lineColor = '#1890ff'

      ctx.strokeStyle = lineColor
      ctx.lineWidth = 2
      ctx.beginPath()
      ctx.moveTo(fromNode.x, fromNode.y)
      ctx.lineTo(toNode.x, toNode.y)
      ctx.stroke()

      // 绘制传播方向箭头
      const angle = Math.atan2(toNode.y - fromNode.y, toNode.x - fromNode.x)
      const arrowLength = 10
      const arrowAngle = Math.PI / 6

      const arrowX = toNode.x - Math.cos(angle) * toNode.size
      const arrowY = toNode.y - Math.sin(angle) * toNode.size

      ctx.beginPath()
      ctx.moveTo(arrowX, arrowY)
      ctx.lineTo(arrowX - arrowLength * Math.cos(angle - arrowAngle), arrowY - arrowLength * Math.sin(angle - arrowAngle))
      ctx.moveTo(arrowX, arrowY)
      ctx.lineTo(arrowX - arrowLength * Math.cos(angle + arrowAngle), arrowY - arrowLength * Math.sin(angle + arrowAngle))
      ctx.stroke()
    })

    // 绘制节点阴影
    nodes.forEach((node) => {
      ctx.beginPath()
      ctx.arc(node.x + 2, node.y + 2, node.size, 0, 2 * Math.PI)
      ctx.fillStyle = 'rgba(0, 0, 0, 0.3)'
      ctx.fill()
    })

    // 绘制节点
    nodes.forEach((node) => {
      // 绘制外环（感染状态指示）
      ctx.beginPath()
      ctx.arc(node.x, node.y, node.size + 3, 0, 2 * Math.PI)
      ctx.strokeStyle = node.color
      ctx.lineWidth = 2
      ctx.stroke()

      // 绘制主节点
      ctx.beginPath()
      ctx.arc(node.x, node.y, node.size, 0, 2 * Math.PI)
      ctx.fillStyle = node.color
      ctx.fill()

      // 绘制节点边框
      ctx.strokeStyle = '#ffffff'
      ctx.lineWidth = 1
      ctx.stroke()

      // 绘制节点标签
      ctx.fillStyle = '#ffffff'
      ctx.font = 'bold 10px Arial'
      ctx.textAlign = 'center'
      ctx.fillText(node.label, node.x, node.y - node.size - 8)

      // 绘制代数标识
      ctx.fillStyle = 'rgba(255, 255, 255, 0.8)'
      ctx.font = '8px Arial'
      ctx.fillText(`G${node.generation}`, node.x, node.y + node.size + 12)
    })

    // 绘制图例
    const legendY = height - 60
    const legendItems = [
      { color: '#f5222d', text: '源头患者', generation: 'G0' },
      { color: '#faad14', text: '一代传播', generation: 'G1' },
      { color: '#1890ff', text: '二代传播', generation: 'G2' },
      { color: '#52c41a', text: '三代传播', generation: 'G3' }
    ]

    legendItems.forEach((item, index) => {
      const x = 20 + index * 120

      ctx.beginPath()
      ctx.arc(x + 8, legendY, 6, 0, 2 * Math.PI)
      ctx.fillStyle = item.color
      ctx.fill()

      ctx.fillStyle = '#ffffff'
      ctx.font = '10px Arial'
      ctx.textAlign = 'left'
      ctx.fillText(item.text, x + 18, legendY + 3)
      ctx.fillText(item.generation, x + 18, legendY + 15)
    })

    // 绘制统计信息
    const statsY = 50
    const totalNodes = nodes.length
    const generations = [...new Set(nodes.map((n) => n.generation))].length

    ctx.fillStyle = 'rgba(255, 255, 255, 0.8)'
    ctx.font = '11px Arial'
    ctx.textAlign = 'left'
    ctx.fillText(`总感染人数: ${totalNodes}`, 20, statsY)
    ctx.fillText(`传播代数: ${generations}`, 20, statsY + 15)
    ctx.fillText(`传播链条: ${connections.length}`, 20, statsY + 30)

    // 绘制标题
    ctx.fillStyle = '#ffffff'
    ctx.font = 'bold 16px Arial'
    ctx.textAlign = 'center'
    ctx.fillText('接触追踪网络', centerX, 25)

    console.log('接触追踪网络绘制完成')
  } catch (error) {
    console.error('绘制接触追踪网络时出错:', error)
  }
}

// 工具方法
const getPlagueColor = (type) => {
  const colors = {
    viral: 'red',
    bacterial: 'orange',
    parasitic: 'purple',
    unknown: 'gray'
  }
  return colors[type] || 'default'
}

const getPlagueName = (type) => {
  const names = {
    viral: '病毒性',
    bacterial: '细菌性',
    parasitic: '寄生虫性',
    unknown: '未知病原'
  }
  return names[type] || type
}

const getSeverityColor = (severity) => {
  const colors = {
    mild: 'green',
    moderate: 'orange',
    severe: 'red',
    critical: 'volcano'
  }
  return colors[severity] || 'default'
}

const getSeverityText = (severity) => {
  const texts = {
    mild: '轻微',
    moderate: '中度',
    severe: '严重',
    critical: '危重'
  }
  return texts[severity] || severity
}

const getMeasureColor = (type) => {
  const colors = {
    物理防控: 'red',
    免疫防护: 'blue',
    环境控制: 'green',
    监测预警: 'orange'
  }
  return colors[type] || 'default'
}

const getCostColor = (cost) => {
  const colors = {
    low: 'green',
    medium: 'orange',
    high: 'red'
  }
  return colors[cost] || 'default'
}

const getCostText = (cost) => {
  const texts = {
    low: '低成本',
    medium: '中等成本',
    high: '高成本'
  }
  return texts[cost] || cost
}

const getR0Description = (r0) => {
  const value = parseFloat(r0)
  if (value < 1) return '疫情可控'
  if (value < 2) return '传播性一般'
  if (value < 3) return '传播性较强'
  return '传播性很强'
}

const getSpeedDescription = (speed) => {
  const descriptions = {
    缓慢: '传播速度较慢',
    中等: '传播速度适中',
    快速: '传播速度较快',
    极快: '传播速度极快'
  }
  return descriptions[speed] || ''
}

const formatDate = (dateString) => {
  return dayjs(dateString).format('MM-DD')
}

const formatTime = (timeString) => {
  return dayjs(timeString).format('HH:mm')
}

// 生命周期
onMounted(async () => {
  try {
    console.log('PlagueManagement组件已挂载，开始初始化...')

    // 确保数据已加载
    await lifeDeathStore.fetchLifeRecords()
    console.log('数据加载完成，specialCases数量:', lifeDeathStore.specialCases.length)

    // 等待DOM更新
    await nextTick()

    // 延迟执行图表绘制，确保元素已完全渲染
    setTimeout(() => {
      console.log('开始绘制图表...')
      drawMapChart()
      drawSpreadChart()
      drawNetworkChart()
    }, 100)
  } catch (error) {
    console.error('初始化图表时出错:', error)
  }
})
</script>

<style lang="scss" scoped>
@use '@/styles/variables.scss' as *;

.plague-management {
  .function-tabs {
    margin-bottom: 24px;
    text-align: center;
  }

  .victim-name {
    font-weight: 500;
    color: $text-primary;
    margin-bottom: 2px;
  }

  .victim-info {
    font-size: 12px;
    color: $text-tertiary;
  }

  .plague-strain {
    font-size: 12px;
    color: $text-secondary;
    margin-top: 4px;
  }

  .timeline-info {
    .timeline-item {
      display: flex;
      font-size: 12px;
      margin-bottom: 2px;

      .label {
        color: $text-secondary;
        width: 40px;
      }

      .date {
        color: $text-primary;
      }
    }
  }

  .risk-levels {
    .risk-item {
      display: flex;
      align-items: center;
      padding: 12px;
      margin-bottom: 12px;
      border-radius: 8px;
      background: rgba(255, 255, 255, 0.05);
      border: 1px solid $border-color;

      .risk-icon {
        font-size: 24px;
        margin-right: 12px;
      }

      .risk-info {
        .risk-title {
          font-weight: 500;
          color: $text-primary;
          margin-bottom: 4px;
        }

        .risk-count {
          font-size: 18px;
          font-weight: bold;
          color: $text-primary;
          margin-bottom: 2px;
        }

        .risk-desc {
          font-size: 12px;
          color: $text-secondary;
        }
      }
    }
  }

  .spread-params {
    .param-item {
      margin-bottom: 20px;
      padding: 12px;
      background: rgba(255, 255, 255, 0.05);
      border-radius: 8px;

      .param-label {
        font-weight: 500;
        color: $text-primary;
        margin-bottom: 4px;
      }

      .param-value {
        font-size: 18px;
        font-weight: bold;
        color: $primary-color;
        margin-bottom: 4px;
      }

      .param-desc {
        font-size: 12px;
        color: $text-secondary;
      }
    }
  }

  .measures-list {
    .measure-item {
      margin-bottom: 20px;
      padding: 16px;
      background: rgba(255, 255, 255, 0.05);
      border: 1px solid $border-color;
      border-radius: 8px;

      .measure-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;

        h4 {
          color: $text-primary;
          margin: 0;
          flex: 1;
        }
      }

      .measure-content {
        p {
          color: $text-secondary;
          margin-bottom: 12px;
        }

        .measure-effectiveness,
        .measure-cost {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-bottom: 8px;
          color: $text-secondary;
        }
      }
    }
  }

  .emergency-actions {
    .emergency-levels {
      .level-item {
        display: flex;
        align-items: center;
        padding: 8px 12px;
        margin-bottom: 8px;
        border-radius: 6px;
        background: rgba(255, 255, 255, 0.05);
        border: 1px solid $border-color;
        transition: all 0.3s ease;

        &.active {
          background: rgba(24, 144, 255, 0.2);
          border-color: #1890ff;
        }

        .level-badge {
          font-weight: bold;
          color: $text-primary;
          margin-right: 12px;
        }

        .level-desc {
          color: $text-secondary;
        }
      }
    }
  }

  .alert-list {
    .alert-item {
      padding: 8px 0;
      border-bottom: 1px solid $border-color;

      &:last-child {
        border-bottom: none;
      }

      .alert-time {
        font-size: 12px;
        color: $text-tertiary;
        margin-bottom: 4px;
      }

      .alert-content {
        font-size: 13px;
        color: $text-secondary;
      }
    }
  }
}
</style>
